package 链表;

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 * @author 会玩的洋洋
 *
 */
public class _2_两数相加 {
	/**
	 * 先将l1和l2的值提取出来，然后相加再加上对应的余数求和
	 * 若大于10，则进位，将余数给当前节点赋值
	 * 如果最后还有进位，则新建一个节点，赋值进位数
	 * @param l1
	 * @param l2
	 * @return
	 */
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
		int remainder = 0;
        while(l1 != null || l2 != null) {
        	int n1 = l1 != null ? l1.val : 0;
        	int n2 = l2 != null ? l2.val : 0;
        	int sum = n1 + n2 + remainder;
        	if (head == null) {
				head = tail = new ListNode(sum % 10);
			}else {
				tail.next = new ListNode(sum % 10);
				tail = tail.next;
			}
        	remainder = sum / 10;
        	if (l1 != null) {
				l1 = l1.next;
			}
        	if (l2 != null) {
				l2 = l2.next;
			}
        }
        if (remainder > 0) {
			tail.next = new ListNode(remainder);
		}
        return head;
    }
}
